<template>
	<section>
		<!--高级查询栏-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="queryData">
				<el-form-item>
					<el-input v-model="queryData.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getEmployee">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFileUpload">导入文件</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFileDownload">导出文件</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--表格-->
    <!--
        v-loading指加载
        @selection-change指的是多选栏
        注意：pageInfo.data中有id，只是没有显示在表格中
    -->
		<el-table :data="pageInfo.data" highlight-current-row @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="40">
			</el-table-column>
			<el-table-column prop="username" label="用户名" width="80" sortable>
			</el-table-column>
      <el-table-column prop="realName" label="姓名" width="100" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="120" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话号码" width="160" sortable>
      </el-table-column>
      <el-table-column prop="salt" label="盐值" width="80" sortable>
      </el-table-column>
      <el-table-column prop="password" label="密码" width="100" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100" sortable>
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.sex == 1" style="color: deepskyblue">男</span>
          <span v-else style="color: lightpink">女</span>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: lightgreen">正常</span>
          <span v-else-if="scope.row.state == 2" style="color: green">锁定</span>
          <span v-else style="color: darkgrey">注销</span>
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门" width="100" sortable>
      </el-table-column>
      <el-table-column prop="loginInfoId" label="注册信息id" width="50" sortable>
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页条和删除全部数据-->
    <!-- 分页条根据数据总条数和每页的数据条数来计算需要分多少页
         @current-change="handleCurrentChange"指的是当前的分页条，点击之后可以更换页面
    -->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size=queryData.pageSize :total="pageInfo.total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增/修改弹框界面-->
    <!--
        对话框的显示也是一个布尔值控制的，但是不能用v-model绑定
        :visible.sync这个属性是控制对话框显示的
    -->
		<el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="用户名" prop="username">
					<el-input v-model="saveForm.username" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="姓名" prop="realName">
        <el-input v-model="saveForm.realName" auto-complete="off"></el-input>
      </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="盐值" prop="salt">
          <el-input v-model="saveForm.salt" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-input v-model="saveForm.sex" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-input v-model="saveForm.state" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="department.name">
          <el-select v-model="saveForm.department" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              下拉框绑定的是管理员对象
              departmentData是部门数组
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in departmentData"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="注册信息id" prop="loginInfoId">
          <el-input v-model="saveForm.loginInfoId" auto-complete="off"></el-input>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

<!--    上传文件界面-->
    <el-dialog title="上传文件" :visible.sync="uploadFormVisible" :close-on-click-modal="false">
      <el-form>
        <el-form-item>
          <el-upload
              class="upload-demo"
              action="/api/employee/upload"
              ref="upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :on-change="handleChange"
              :on-success="onSuccess"
              :on-error="onError"
              :on-exceed="handleExceed"
              multiple
              :limit="3"
              :file-list="fileList"
              :auto-upload="false">
            <el-button slot="trigger" type="primary" >点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="uploadFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="uploadSubmit" :loading="uploadLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<script>
/* mockjs的随机生成数据的内容，请求后端接口就不用mockjs了，有了mockjs就不会请求后端接口 */
	// import util from '../../common/js/util'
	// //import NProgress from 'nprogress'
	// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
			  /* 分页查询传到后端的数据 */
        queryData: {
					keyword: '', //使用了视图与模型双向绑定，视图的值改变，模型的值也会随之改变
          pageSize: 10,
          currentPage: 1
				},
        /* 分页查询返回前端的数据 */
        pageInfo: {
          data: [],
          total: 0,
        },
        /* 后端查到的部门数据列表 */
        departmentData:[],
        /* 后端查到的父部门数据列表 */
        deptTree:[],

				page: 1,
				listLoading: false,
				sels: [],//列表选中列

        saveFormVisible: false,//编辑界面是否显示
        uploadFormVisible: false, //上传文件界面是否显示

				addFormVisible: false,//新增界面是否显示
				saveLoading: false,
        uploadLoading: false,
        saveFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					]
				},

        /* 新增/修改界面需要绑定的属性数据 */
        saveForm: {
          id:null,
          username:'',
          realName:'',
          email:'',
          phone:'',
          salt:'',
          password:'',
          age:null,
          sex:1,
          state:null,
          department:{
            id:null,
            name:''
          },
          loginInfoId:null
        },
        /* 文件上传路径 */
        fileList: []
			}
		},
		methods: {
		  /* 导出数据 */
      handleFileDownload() {
          //通过选中的行的id列表和关键字导出
          this.$http.get("/employee/download/"+this.queryData.keyword)
              .then(res => {
                res = res.data;
                console.log(res);
                if (res.success){
                  this.$message.success("成功导出文件");
                }else {
                  this.$message.error("导出文件失败");
                }
              })
        },
      /* 上传成功后的操作 */
      onSuccess(res, file,fileList) {
        if (res.success){
          this.$message.success('上传成功');
          console.log(res.data)
        }else {
          this.$message.error(res.msg)
        }
      },
      /* 上传失败的操作 */
      onError(res,error) {
        this.$message.error('上传失败');
        // 处理上传失败的逻辑
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleChange(file,fileList) {
        console.log(file)
        console.log(fileList)
      },

		  /* 文件导入按钮 */
      handleFileUpload() {
        this.uploadFormVisible = true;
      },
      /* 文件导入数据库 */
      uploadSubmit() {
        this.$refs.upload.submit();
        this.uploadFormVisible = false;
        this.uploadFormVisible = false;
        //查询文件导入之后的所有数据
        this.getEmployee();
      },
      /* 改变当前页面时显示不同数据 */
      handleCurrentChange(val) {
        //val指的是当前的页数
        this.queryData.currentPage = val //点击之后更改页数，再根据修改后的页数查询所有数据
        this.getEmployee();
      },
      /* 获取员工列表 */
      getEmployee() {
        //获取参数-currentPage, pageSize, keyword
        //发起请求（直接向后端发起Ajax请求会触发跨域问题，出于安全考虑，浏览器会阻止js发起Ajax请求）
        this.$http.post("/employee",this.queryData)
            .then((result) => {
              var result = result.data;
              if (result.success){
                //请求成功
                //此处的result的total查询的一直是数据库数据的总条数，data是每一页的不同数据
                this.pageInfo = result.data  //将返回的数据赋值给组件中的data
              }else {
                this.$message.error("网络异常请联系管理员")
              }
            })
            .catch((result) => {

            })
      },
      /* 删除按钮 */
      handleDel: function (index, row) {
        //row是改行的数据
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //发起请求
          this.deleteEmployee(row.id);
        }).catch(() => {

        });
      },
      /* 删除的方法 */
      deleteEmployee(id){
        this.$http.delete("/employee/"+id)
            .then((result) => {
              result = result.data
              if (result.success){
                this.$message({message:"删除成功",type:"success"});
                this.listLoading = false;  //删除数据之后隐藏加载框
                this.queryData.currentPage = 1;//删除成功之后将当前页面置为1再从数据库的第一条数据查起，否则返回的全部数据
                this.getEmployee();
              }else {
                this.$message.error("网络异常请联系管理员")
              }
            }).catch()
      },
      /* 显示编辑界面 */
      handleEdit(index, row) {
        //将表格中列的数据传过来，赋值给saveForm后再双向绑定在编辑页面中用于数据的回显
        this.saveFormVisible = true;  //显示编辑页面
        this.saveForm = Object.assign({}, row);  //当前列对象
        this.getDepartment();
      },

      /* 查询所有部门数据的方法 */
      getDepartment() {
        this.$http.get("/department")
            .then(result => {
              result = result.data
              if (result.success){
                this.departmentData = result.data; //将查询到的部门数据赋值给departmentData
              }
            })
      },
      /* 显示新增界面 */
      handleAdd: function () {
        this.saveFormVisible = true; //显示编辑界面
        //清空数据，新增和修改使用的是同一个弹框，如果不清空，点修改后数据不会清空
        this.saveForm = {
          id:null,
          username:'',
          realName:'',
          email:'',
          phone:'',
          salt:'',
          password:'',
          age:null,
          sex:1,
          state:null,
          department:{
            id:null,
            name:''
          },
          loginInfoId:null
        };
        this.getDepartment();
      },

      /* 新增/修改编辑提交按钮 */
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              this.saveFormVisible = false;
              //发起请求
              this.insertOrUpdate();
              this.saveLoading = false;
            });
          }
        });
      },

      /* 新增或修改的方法 */
      insertOrUpdate(){
        //点击确定提交即把修改后的数据提交到后台
        this.$http.put("/employee",this.saveForm)
            //this.saveForm是编辑界面修改过后的值
            .then((result) => {
              result = result.data
              if (result.success){
                this.$message({message:"保存成功",type:"success"});
                this.queryData.currentPage = 1;//修改在其他页当前页码不是1，查询的时候不会查询所有数据，因此将当前页重新设置为1再查
                this.getEmployee();
              }else {
                this.$message.error("网络异常请联系管理员")
              }
            }).catch();
      },

      selsChange: function (sels) {
        //sele是多选栏每一栏选中的行对象
        var ids = sels.map(x => x.id);
        this.sels = ids //将储存有数据对象的数组赋值为id
      },
      /* 批量删除按钮 */
      batchRemove: function () {
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //发起请求
          this.batchDelete(this.sels); //this.sels是要删除的id数组
        }).catch(() => {
        });
      },
      //批量删除的方法
      batchDelete(ids){
        this.$http.patch("/employee/",ids)
            .then((result) => {
              result = result.data
              if (result.success){
                this.$message({message:"删除成功",type:"success"});
                this.listLoading = false;  //删除数据之后隐藏加载框
                this.queryData.currentPage = 1;
                this.getEmployee();
              }else {
                this.$message.error("网络异常请联系管理员")
              }
            }).catch()
      }
    },
    mounted() {
      this.getEmployee();
    }
	}

</script>

<style scoped>

</style>